/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { X2DBeta } = require("../graphics/X2DInterface");
const { Scr } = require("../XDefine");
const { XStat } = require("../XStat");

class XWindow {
    constructor(name = "XWindow", full = true) {
        this.name_ = name;
        this.fullScreen_ = full;
        this.uis_ = [];
        this.x_ = 0;
        this.y_ = 0;
        this.w_ = -1;
        this.h_ = -1;
    }
    addUI(ui) {
        this.uis_.push(ui);
    }
    clearUI() {
        this.uis_ = [];
    }
    reInit() {
    }
    onDraw() {
        if (this.w_ > 0 && this.h_ > 0) {
            X2DBeta.fillRect(this.x_ + 10, this.y_ + 10, this.w_, this.h_, 0x80303030);
            X2DBeta.fillRect(this.x_, this.y_, this.w_, this.h_, 0x80300000);
            X2DBeta.drawRect(this.x_, this.y_, this.w_, this.h_, 0xffffffff);
        }
        for (let i = 0; i < this.uis_.length; i++) {
            let ui = this.uis_[this.uis_.length - 1 - i];
            ui.onDraw(this.x_, this.y_);
        }
    }
    onTouch(msg, x, y) {
        x -= this.x_;
        y -= this.y_;
        for (let ui of this.uis_) {
            if (ui.onTouch(msg, x, y)) {
                return true;
            }
        }
        if (x >= 0 && x < this.w_ && y >= 0 && y < this.h_) {
            return true;
        }
        else {
            // if (msg == 3) {
            //     XStat.popStat();
            // }
            return true;
        }
        if (this.fullScreen_) {
            return true;
        }
    }
    onKey(type, k) {
        if (type==1 && k == 'Escape') {
            XStat.popStat();
            return true;
        }
        if (this.fullScreen_) {
            return true;
        }
    }
    OnMessage(msg) {
        switch (msg.protocol) {
        }
        if (this.fullScreen_) {
            return true;
        }
    }
    resizeCenter(w, h) {
        this.x_ = (Scr.logicw - w) / 2;
        this.y_ = (Scr.logich - h) / 2;
        this.w_ = w;
        this.h_ = h;
    }
    close() {
        XStat.popStat();
    }
    static open() {
        let p = XStat.SearchStat("XWindow");
        if (p) {
            p.reInit();
        }
        else {
            XStat.pushStat(new XWindow());
        }
    }
}

module.exports = {
    XWindow
}